package com.niezhiliang.netty.websocket.spring.boot.demo.service.other.handler;

import com.niezhiliang.netty.websocket.spring.boot.demo.utils.DataUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledUnsafeDirectByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

public class NettyClientHandler extends SimpleChannelInboundHandler<io.netty.channel.socket.DatagramPacket> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String fixStr = "client channel is active";
        ByteBuf byteBuf = DataUtil.strToDirectByteBuf(fixStr);
        ctx.writeAndFlush(byteBuf);
        byteBuf.clear();
    }



    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        System.out.println("from server:"+msg.content().toString(CharsetUtil.UTF_8));
    }


}
